//
//  UIDevice+IdentifierAddition.m
//  JQKit
//
//  Created by JQZ on 2017/12/28.
//  Copyright © 2017年 JQZ. All rights reserved.
//

#import "UIDevice+IdentifierAddition.h"
#import <Security/Security.h>

NSString * const KEY_UDID_INSTEAD = @"com.app.udid";

@implementation UIDevice (IdentifierAddition)

- (NSString *) uniqueDeviceIdentifier
{
    NSString *UUID = (NSString *)[self p_keychain_load:KEY_UDID_INSTEAD];
    if (UUID == nil || UUID.length == 0) {
        UUID = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
        [self p_keychain_save:KEY_UDID_INSTEAD data:UUID];
    }
    
    return UUID;
}

#pragma mark - private

- (NSMutableDictionary *)p_keychain_getKeychainQuery:(NSString *)service
{
    return [NSMutableDictionary dictionaryWithObjectsAndKeys:
            (id)kSecClassGenericPassword,(id)kSecClass,
            service, (id)kSecAttrService,
            service, (id)kSecAttrAccount,
            (id)kSecAttrAccessibleAfterFirstUnlock,(id)kSecAttrAccessible,
            nil];
}

- (void)p_keychain_save:(NSString *)service data:(id)data
{
    //Get search dictionary
    NSMutableDictionary *keychainQuery = [self p_keychain_getKeychainQuery:service];
    //Delete old item before add new item
    SecItemDelete((CFDictionaryRef)keychainQuery);
    //Add new object to search dictionary(Attention:the data format)
    [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(id)kSecValueData];
    //Add item to keychain with the search dictionary
    SecItemAdd((CFDictionaryRef)keychainQuery, NULL);
}

- (id)p_keychain_load:(NSString *)service
{
    id ret = nil;
    NSMutableDictionary *keychainQuery = [self p_keychain_getKeychainQuery:service];
    [keychainQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];
    [keychainQuery setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit];
    CFDataRef keyData = NULL;
    if (SecItemCopyMatching((CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) {
        @try {
            ret = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)keyData];
        } @catch (NSException *e) {
            NSLog(@"Unarchive of %@ failed: %@", service, e);
        } @finally {
        }
    }
    if (keyData)
        CFRelease(keyData);
    return ret;
}

- (void)p_keychain_delete:(NSString *)service
{
    NSMutableDictionary *keychainQuery = [self p_keychain_getKeychainQuery:service];
    SecItemDelete((CFDictionaryRef)keychainQuery);
}

@end
